package com.github.cyf.common.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.github.cyf.common.util.DateUtil;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author chenyifan
 * @create 2024-09-29 11:24
 */
public class LocalDateTimeStringConverter implements Converter<LocalDateTime> {

    public static final LocalDateTimeStringConverter INSTANCE = new LocalDateTimeStringConverter();

    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)  {
        String value = cellData.getStringValue();
        if (!StringUtils.hasText(value)) {
            return null;
        }
        return DateUtil.parseDateTime(value);
    }
    @Override
    public WriteCellData<?> convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        WriteCellData cellData = new WriteCellData();
        cellData.setType(CellDataTypeEnum.STRING);
        if (Objects.isNull(localDateTime)) {
            cellData.setStringValue("");
        } else {
            cellData.setStringValue(DateUtil.format(localDateTime));
        }
        return cellData;
    }
}
